﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace PKTools
{
    public class LazyCache<TKey, TValue>
    {
        readonly static ThreadLocal<Dictionary<TKey, TValue>>
            _objects;
        readonly Func<TKey, TValue>
            notFoundF;

        static LazyCache()
        {
            _objects = new ThreadLocal<Dictionary<TKey, TValue>>(() => new Dictionary<TKey, TValue>());
        }

        public LazyCache(Func<TKey, TValue> notFoundF)
        {
            this.notFoundF = notFoundF;
        }

        public TValue Get(TKey key)
        {
            TValue
                value;

            if (_objects.Value.TryGetValue(key, out value))
                return value;

            value = this.notFoundF(key);
            _objects.Value.Add(key, value);

            return value;
        }

        public void Clear()
        {
            _objects.Value.Clear();
        }
    }
}
